package com.dlxj.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.dlxj.dao.BaseDAO;
import com.dlxj.entity.Bugtype;
import com.dlxj.entity.Patroltask;
import com.dlxj.entity.PatroltaskUser;
import com.dlxj.entity.Pole;
import com.dlxj.entity.Receiptpatrol;
import com.dlxj.entity.User;
import com.dlxj.service.PatrolTaskService;
import com.dlxj.service.PoleService;
import com.dlxj.util.ConstClass;
import com.dlxj.util.PageBean;
import com.dlxj.util.excel.ExportExcel;
import com.dlxj.util.excel.ExportExcelBean;

public class PatrolTaskServiceImpl implements PatrolTaskService {

	BaseDAO baseDAO;
	PoleService poleService;
	ExportExcelBean exportExcelBean;

	@Override
	public int addPatrolTast(Patroltask patroltask, List<User> users) {
		try {
			int count = baseDAO.countHql(
					"select count(*) from Patroltask where id = ?",
					new Object[] { patroltask.getId() });
			if (count > 0) {
				//检测是否已制定
				return 3;
			}
			count = poleService
					.findPoliesByStartPoleIdAndEndStartPoleIdAndCircuitryId(
							patroltask.getStartPoleNo(), patroltask.getEndPoleNo(),
							patroltask.getCid()).size();
			if (count == 0) {
				return ConstClass.ADD_FAILURE;
			}
			patroltask.setCancel(1);
			if (users == null || users.size() == 0) {
				patroltask.setState(ConstClass.TASK_STATE_WAIT);// 待分配
			} else {
				patroltask.setState(ConstClass.TASK_STATE_ASSIGNED);// 已分配
			}
			patroltask.setTime(new Date());// 设置当前时间
			patroltask.setUid(ConstClass.getCurrentUser().getId());// 设置当前用户
			String pid = (String) baseDAO.save(patroltask);// 保存任务
			for (User user : users) { // 保存用户列表
				PatroltaskUser pu = new PatroltaskUser();
				pu.setPid(pid);
				pu.setUid(user.getId());
				baseDAO.save(pu);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ConstClass.ADD_SUCCESS;
	}

	
	
	public BaseDAO getBaseDAO() {
		return baseDAO;
	}

	public void setBaseDAO(BaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}

	public PoleService getPoleService() {
		return poleService;
	}

	public void setPoleService(PoleService poleService) {
		this.poleService = poleService;
	}

	@Override
	public List<Patroltask> findWaitStatePatrol() {
		List<Patroltask> patroltasks = (List<Patroltask>) baseDAO.findByHql(
				"from Patroltask where  state =? and cancel =?", new Object[] {
						ConstClass.TASK_STATE_WAIT, ConstClass.ENABLE });
		for (Patroltask patroltask : patroltasks) {
			List<Pole> polies = poleService
					.findPoliesByStartPoleIdAndEndStartPoleIdAndCircuitryId(
							patroltask.getStartPoleNo(),
							patroltask.getEndPoleNo(), patroltask.getCid());
			patroltask.setPolies(polies);
		}
		return patroltasks;
	}

	@Override
	public List<Patroltask> findTaskNoByPid(String state, String pid) {
		Object[] param = null;
		if (state != null) {
			param = new Object[] { ConstClass.ENABLE, state };
		}
		List<Patroltask> result = new ArrayList<Patroltask>();
		List<Patroltask> patroltasks = (List<Patroltask>) baseDAO.findByHql(
				"from Patroltask where  cancel =? "
						+ (state == null ? " " : " and state =?"), param);
		for (Patroltask patroltask : patroltasks) {
			int count = baseDAO
					.countHql(
							"select count(*) from CircuitryPole where cid = ? and pid =?",
							new Object[] { patroltask.getCid(), pid });
			if (count > 0) {
				result.add(patroltask);
			}
		}
		return result;
	}

	@Override
	public int assignUser(String tid, String uids) {
		String[] ids = null;
		if (uids != null && uids.length() > 0) {
			ids = uids.split(",");
		} else {
			return ConstClass.ADD_FAILURE;
		}
		List<PatroltaskUser> pus = (List<PatroltaskUser>) baseDAO.findByHql(
				"from PatroltaskUser where pid=?", new Object[] { tid });
		for (PatroltaskUser patroltaskUser : pus) {
			baseDAO.delete(PatroltaskUser.class, patroltaskUser.getId());
		}
		for (String uid : ids) {
			PatroltaskUser pu = new PatroltaskUser();
			pu.setUid(Integer.valueOf(uid));
			pu.setPid(tid);
			baseDAO.save(pu);
		}
		Patroltask patroltask = (Patroltask) baseDAO.findById(Patroltask.class,
				tid);
		patroltask.setState(ConstClass.TASK_STATE_ASSIGNED);
		baseDAO.save(patroltask);
		return ConstClass.ADD_SUCCESS;
	}

	@Override
	public List<Patroltask> findAssignedList() {
		int id = ConstClass.getCurrentUser().getId();
		List<Patroltask> patroltasks = (List<Patroltask>) baseDAO
				.findByHql(
						"from Patroltask where state = ? and id in ( select pid from PatroltaskUser where uid =? ) ",
						new Object[] { ConstClass.TASK_STATE_ASSIGNED, id });
		for (Patroltask patroltask : patroltasks) {
			List<Pole> polies = poleService
					.findPoliesByStartPoleIdAndEndStartPoleIdAndCircuitryId(
							patroltask.getStartPoleNo(),
							patroltask.getEndPoleNo(), patroltask.getCid());
			patroltask.setPolies(polies);
		}
		return patroltasks;
	}

	@Override
	public List<Patroltask> findTaskNoByPidAndUid(String state, String pid,
			int uid) {
		List<Patroltask> patroltasks = this.findTaskNoByPid(state, pid);
		List<Patroltask> result = new ArrayList<Patroltask>();
		for (Patroltask patroltask : patroltasks) {
			int count = baseDAO
					.countHql(
							"select count(*) from PatroltaskUser where pid = ? and uid = ?",
							new Object[] { patroltask.getId(), uid });
			if (count > 0) {
				result.add(patroltask);
			}
		}
		return result;
	}

	@Override
	public int executeTask(String TaskNo) {
		Patroltask patroltask = (Patroltask) baseDAO.findById(Patroltask.class,
				TaskNo);
		patroltask.setState(ConstClass.TASK_STATE_EXECUTING);
		baseDAO.update(patroltask);
		return ConstClass.UPDATE_SUCCESS;
	}

	@Override
	public List<Patroltask> findExecutingList() {
		int id = ConstClass.getCurrentUser().getId();
		List<Patroltask> patroltasks = (List<Patroltask>) baseDAO
				.findByHql(
						"from Patroltask where state = ? and id in ( select pid from PatroltaskUser where uid =? ) ",
						new Object[] { ConstClass.TASK_STATE_EXECUTING, id });
		for (Patroltask patroltask : patroltasks) {
			List<Pole> polies = poleService
					.findPoliesByStartPoleIdAndEndStartPoleIdAndCircuitryId(
							patroltask.getStartPoleNo(),
							patroltask.getEndPoleNo(), patroltask.getCid());
			for (Pole pole : polies) {
				List<Receiptpatrol> receiptpatrols = (List<Receiptpatrol>) baseDAO
						.findByHql(
								"from Receiptpatrol where ptid =? and pid=?",
								new Object[] { patroltask.getId(), pole.getId() });
				if (receiptpatrols.size() > 0) {
					pole.setReceiptpatrol(receiptpatrols.get(0));
				}
			}
			patroltask.setPolies(polies);
		}
		return patroltasks;
	}

	@Override
	public List<Patroltask> findFinishList() {
		List<Patroltask> patroltasks = (List<Patroltask>) baseDAO.findByHql(
				"from Patroltask where state = ?",
				new Object[] { ConstClass.TASK_STATE_FINISH });
		for (Patroltask patroltask : patroltasks) {
			List<Pole> polies = poleService
					.findPoliesByStartPoleIdAndEndStartPoleIdAndCircuitryId(
							patroltask.getStartPoleNo(),
							patroltask.getEndPoleNo(), patroltask.getCid());
			for (Pole pole : polies) {
				List<Receiptpatrol> receiptpatrols = (List<Receiptpatrol>) baseDAO
						.findByHql(
								"from Receiptpatrol where ptid =? and pid=?",
								new Object[] { patroltask.getId(), pole.getId() });
				if (receiptpatrols.size() > 0) {
					pole.setReceiptpatrol(receiptpatrols.get(0));
				}

			}
			patroltask.setPolies(polies);
		}
		return patroltasks;
	}

	@Override
	public Patroltask findByTaskNo(String no) {
		return (Patroltask) baseDAO.findById(Patroltask.class, no);

	}

	@Override
	public int sureTask(String taskNo) {
		Patroltask patroltask = (Patroltask) baseDAO.findById(Patroltask.class,
				taskNo);
		patroltask.setState(ConstClass.TASK_STATE_SURE);
		return ConstClass.UPDATE_SUCCESS;
	}

	@Override
	public PageBean statistics(Patroltask patroltask,
			Receiptpatrol receiptpatrol, Date sd, Date ed, int pageIndex,
			int pageSize) {
		String hql = "from Receiptpatrol where ptid in (select id from Patroltask where 1=1 ";
		List<Object> paramList = new ArrayList<Object>();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (!"".equals(patroltask.getCid())) {
			hql += " and cid = ?";
			paramList.add(patroltask.getCid());
		}
		if (patroltask.getUid() != 0) {
			hql += " and uid = ?";
			paramList.add(patroltask.getUid());
		}
		hql += ")";
		if (!"".equals(receiptpatrol.getPid())) {
			hql += " and pid =?";
			paramList.add(receiptpatrol.getPid());
		}
		if (receiptpatrol.getUid() != 0) {
			hql += " and ptid in(select pid from PatroltaskUser where uid = ?)";
			paramList.add(receiptpatrol.getUid());
		}
		if (receiptpatrol.getLevel() != 0) {
			hql += " and level = ?";
			paramList.add(receiptpatrol.getLevel());
		}
		if (receiptpatrol.getBid() != 0) {
			hql += " and bid = ?";
			paramList.add(receiptpatrol.getBid());
		}
		if (sd != null) {
			hql += " and time >=?";
			paramList.add(sd);
		}
		if (sd != null) {
			hql += " and time <=?";
			paramList.add(ed);
		}
		hql += " order by time desc";
		PageBean bean = baseDAO.findPageBeanHQL(hql, pageIndex, pageSize,
				paramList.toArray()); 
		List<Receiptpatrol> list = bean.getRows();
		String[] level = { "", "一般", "严重", "紧急" };
		for (Receiptpatrol receipt : list) {
			Patroltask task = (Patroltask) baseDAO.findById(Patroltask.class,
					receipt.getPtid());
			Bugtype bt = (Bugtype) baseDAO.findById(Bugtype.class,
					receipt.getBid());
			receipt.setTypeName(bt.getName());
			User user = (User) baseDAO.findById(User.class, receipt.getUid());
			receipt.setUserName(user.getName());
			user = (User) baseDAO.findById(User.class, task.getUid());
			task.setUserName(user.getName());
			receipt.setLevelName(level[receipt.getLevel()]);
			receipt.setPatroltask(task);

		}
		bean.setRows(list);

		return bean;
	}

	@Override
	public String export(Patroltask patroltask, Receiptpatrol receiptpatrol,
			Date sd, Date ed) {
		PageBean bean = this.statistics(patroltask, receiptpatrol, sd, ed, 1,
				999999);
		if (bean.getTotal() == 0) {
			return "";
		}
		String fileName = "";
		try {
			exportExcelBean.setDataSource(bean.getRows());
			exportExcelBean.setTitle("巡检记录统计表");
			ExportExcel excel = new ExportExcel(exportExcelBean);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			fileName = sdf.format(new Date());
			excel.export(ServletActionContext.getRequest().getRealPath("")
					+ "\\xls\\" + fileName + ".xls");
		} catch (Exception e) {
			return "";
		}
		return fileName;

	}

	public ExportExcelBean getExportExcelBean() {
		return exportExcelBean;
	}

	public void setExportExcelBean(ExportExcelBean exportExcelBean) {
		this.exportExcelBean = exportExcelBean;
	}

}
